package ifpb.banco.DAO;

import ifpb.banco.entity.Identificavel;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
 *
 * @author Vanderlan
 */
@SuppressWarnings("unchecked")
public class GenericDAO <T extends Identificavel> {
    
  
    protected static EntityManager entityManager;
 
    static {
        EntityManagerFactory fac = Persistence
                .createEntityManagerFactory("Projeto-Banco-dados-IPU");
        entityManager = fac.createEntityManager();
    }
 
    public T getById(Integer id) {
        Long idTemp =  Long.valueOf (id);
        return (T) entityManager.find(getTypeClass(), idTemp);
    }
 
    public void save(T entity) {
        try {
            entityManager.getTransaction().begin();
            entityManager.persist(entity);
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            entityManager.getTransaction().rollback();
        }
    }
 
    public void update(T entity) {
        try {
            entityManager.getTransaction().begin();
            entityManager.merge(entity);
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            entityManager.getTransaction().rollback();
        }
    }
 
    public void delete(T entity) {
        try {
            Integer i = (int) (long) entity.getId();
            entity = getById(i);
            entityManager.getTransaction().begin();
            entityManager.remove(entity);
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            entityManager.getTransaction().rollback();
        }
    }
 
    public Collection<T> listarTodos() {
        return entityManager.createQuery(("From " + getTypeClass().getName()))
                .getResultList();
    }
 
    private Class<?> getTypeClass() {
        Class<?> clazz = (Class<?>) ((ParameterizedType) this.getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
        return clazz;
    }
}

